<template>
	<div ref="useTable"></div>
</template>

<script setup>
	import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
	
	const { proxy } = getCurrentInstance()
	
	const height = ref(0)
	const tblHeight = ref(0)
	const body = ref(null)
	let containers = reactive([])
	const tableObj = ref(null)
	const tableHeadHeight = ref(0)
	const tablePaginationHeight = ref(0)
	const useTable = ref(null)
	
	const { tableRefs, navHeight, bottom, right, top } = defineProps({
	  tableRefs: {
	    type: Object,
	    default: null
	  },
		navHeight: {
			type: Number,
			default: 0
		},
		bottom: {
			type: Number,
			default: 16
		},
		right: {
			type: Number,
			default: 16
		},
		top: {
			type: Number,
			default: 0
		}
	})
	
	const tableStyle = () => {
		if (tableObj.value && tableObj.value.ele) {
			return
		}
		
		containers.forEach(ele => {
			// 16 间距
			if (![...ele.classList].includes('use-table')) {
				height.value -= ele.clientHeight - 16
			} else {
				tableObj.value = {
					offset: proxy.$api.offset(ele),
					ele
				}
			}
		})
		
		if (tableObj.value.ele.childNodes.length) {
			tableObj.value.ele.childNodes.forEach(ele => {
				if ([...ele.classList].includes('table-head')) {
					let getComputedStyle = window.getComputedStyle(ele);
					tableHeadHeight.value = ele.offsetHeight + parseInt(getComputedStyle.marginBottom);
				} else if ([...ele.classList].includes('el-pagination')) {
					tablePaginationHeight.value = ele.offsetHeight
				}
			})
		}
	}
	
	const tableInit = (height) => {
		tableObj.value.ele.style.position = 'initial'
		tableObj.value.ele.style.height = tableObj.value.ele.clientHeight + height + 'px'
	}
	
	const tableChange = () => {
		tableObj.value.offset = proxy.$api.offset(tableObj.value.ele)
		tableObj.value.ele.style.position = 'fixed'
		tableObj.value.ele.style.top = tableObj.value.offset.t + 'px'
		tableObj.value.ele.style.left = tableObj.value.offset.l + 'px'
		tableObj.value.ele.style.bottom = bottom + 'px'
		tableObj.value.ele.style.right = right + 'px'
		// 40 为上下 padding 20
		tblHeight.value = (parseInt(tableObj.value.ele.style.height) || tableObj.value.ele.clientHeight) - 40 - tableHeadHeight.value - tablePaginationHeight.value
		tableObj.value.ele.querySelector('.el-table').style.height = tblHeight.value + 'px'
	}
	
	onMounted(() => {
		uni.$on('fold', res => {
			if (res) {
				tableObj.value.ele.style.left = 'calc(16px + var(--window-left))'
			} else {
				tableObj.value.ele.style.left = 'calc(16px + var(--window-left))'
			}
		})
		
		body.value = document.getElementsByTagName('uni-page-body')[0]
		height.value = body.clientHeight
		
		containers = useTable.value.parentElement.querySelectorAll('.container')
		
		tableStyle()
		tableChange()
		
		window.onresize = () => {
			if (tableRefs) {
				tableRefs.doLayout()
			}
			tableChange()
		}
	})
	
	defineExpose({
	  tblHeight
	})
</script>

<style></style>
